using System;
using System.Collections.Generic;
using UnityEngine;
using Yoozoo.Gameplay.RTS;
using Yoozoo.Managers.ResourceManagerV2.Runtime;
using Object = UnityEngine.Object;

namespace WorldMapBase.Tile.Pool
{
    public class RtsInstanceModelPool : ObjectPool<ModelInstaning>
    {
        public int index;
        private int _initNum;
        private GameObject prefab;
        private Transform parentTrans;
        private string path;
        private Action onLoadOver;
        private bool Ready = false;
        private ResLoader _resLoader;
        
        private static readonly Color MODEL_COLOR = new Color(150f / 255f, 150f / 255f, 150f / 255f, 1f);

        private HashSet<ModelInstaning> m_usingList;
        
        public RtsInstanceModelPool(int capacity,
            int initNum,
            ResLoader resLoader, 
            int index,
            string path, 
            Transform parentTrans,
            Action onLoadOver = null) : base(capacity,true,10,20,10f)
        {
#if UNITY_EDITOR
            var strs = path.Split('/');
            _name = "RtsInstanceModelPool: " + strs[strs.Length - 1];
#endif
            
            m_usingList = new HashSet<ModelInstaning>();
            this._resLoader = ResLoader.Alloc();
            this.index = index;
            this._initNum = initNum;
            this.onLoadOver = onLoadOver;
            this.path = path;
            this.parentTrans = parentTrans;
        }

        protected override ModelInstaning ConstructItem()
        {
            try
            {
                GameObject tempObject = Object.Instantiate(prefab, parentTrans);
                tempObject.SetActive(false);
                ModelInstaning model = tempObject.GetComponent<ModelInstaning>();
                if (model != null)
                {
                    ((IModel)model).OnCreate();
                    int instanceId = model.SetConfig(index, 100000, 1);
                    model.poolKey = index;
                    model.SetMainColor(instanceId, MODEL_COLOR);
                    model.SetAnimatorEnabled(false);
                    model.transform.position = new Vector3(99999, 99999, 99999); //new Vector3(instanceNum++, 999, index);
                }
                else
                {
                    UnityEngine.Debug.LogErrorFormat("创建ModelInstancing失败 {0}", this.path);
                }
                return model;
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogError(path + e.StackTrace);
                throw;
            }
            
        }

        protected override void BeforeRecover(ModelInstaning instanceMod)
        {
            IModel model = (IModel)instanceMod;
            
            var trans = model.GameObject.transform;
            trans.SetParent(parentTrans);
            model.SetAnimatorTrigger(GameFramework.Battle.Core.EAnimationType.ani_Stand_Idle,false);
            instanceMod.SetAlpha(1);
            instanceMod.SetAnimatorEnabled(false);
            m_usingList.Remove(instanceMod);
            trans.position = new Vector3(0, 99999, 0);
        }

        public bool IsReady()
        {
            return Ready;
        }
        
        public void StartLoading()
        {
            _resLoader.Add2Load("Assets/ResourcesAssets/" + path, (success, name, asset) =>
            {
                if (asset == null)
                {
                    return;
                }

                if (success)
                {
                    prefab = asset as GameObject;
                    OnInit(_initNum);
                    Ready = true;
                    if (onLoadOver != null)
                    {
                        onLoadOver();
                    }
                }
            });
            var prefabNames = path.Split('/');
            var prefabName = prefabNames[prefabNames.Length - 1];
            var assetName = prefabName.Replace("_inst.prefab", ".asset");

            _resLoader.Add2Load("Assets/ResourcesAssets/Config/RTSScriptConfig/"+assetName, (success, name, asset) =>
            {
                if (asset == null)
                {
#if true
                    Debug.LogError("name:" + "加载失败");
#endif
                    return;
                }

                if (success)
                {
                    BattleUtils.AddBoneInfo(index,asset as GPUSkinning_BoneNode);
                }
            });
            _resLoader.Load();
        }


        protected override void OnGetObject(ModelInstaning model)
        {
            model.SetAnimatorEnabled(true);
            ((IModel) model).SetAnimatorTrigger(GameFramework.Battle.Core.EAnimationType.ani_Stand_Idle,false);
        }

        protected override void OnBeforeDestroy()
        {
            foreach (var obj in _objects)
            {
                Object.Destroy(obj.gameObject);
            }
            
            foreach (var modelInstaning in m_usingList)
            {
                Object.Destroy(modelInstaning.gameObject);
            }
            m_usingList.Clear();
            _resLoader.Recycle2Cache();
            _resLoader = null;
            prefab = null;
            BattleUtils.RemoveBoneInfo(index);

            GPUInstancingManager.RemoveInstancingConfig(index + 100000);
            Ready = false;
        }
        
    }
}
